import util from '@/util'
import defaultHeadIcon from "@/assets/images/default-avatar.png";
import { Login, Authorize, DataItem, Manaframe, Department, UserCenter } from "@/api";
import { filterAsyncRouter, mergeRoutes } from "@/router/dynamic_routes"
import router from "@/router/index"

const user = {
    state: {
        userinfo: {},
        menulist: [],
        buttonlist: [],
        authRoutes: [],
        manalist: [],
        deplist: [],
        dataitemlist: [],
        token: util.getStore({ name: 'token' }) || '',
        tokenexpire: util.getStore({ name: 'tokenexpire' }) || null,
        tokensilde: util.getStore({ name: 'tokensilde' }) || null,
    },
    actions: {
        //用户登录
        LoginByUsername({ dispatch, commit }, param) {
            return new Promise((resolve, reject) => {
                Login.GetJwt(param).then((res) => {
                    commit("SET_TOKENREFERENCE", { token: res.token, tokenexpire: res.expires_in });
                    dispatch("DataReload").then((res) => { resolve() }).catch(error => { reject(error) });//数据重载
                }).catch(error => {
                    reject(error)
                })
            })
        },
        //退出登录
        Logout({ dispatch, commit }) {
            dispatch("ClearStore"); //清除用户缓存数据
            //清除路由数据
            window.location.reload();
            //router.replace('/login'); //返回登陆页面
        },
        //刷新token
        RefeshToken({ state, commit }) {
            return new Promise((resolve, reject) => {
                Login.RefreshToken({ token: state.token }).then((res) => {
                    commit("SET_TOKENREFERENCE", { token: res.token, tokenexpire: res.expires_in });
                    resolve();
                }).catch(error => {
                    reject(error)
                })
            })
        },
        //数据重载
        DataReload({ commit, rootState }) {
            return new Promise((resolve, reject) => {
                Promise.all([
                    Authorize.GetAuthList().then((res) => {
                        commit("SET_MENULIST", res.MenuList);
                        commit("SET_BUTTONLIST", res.ButtonList);
                    }),
                    Manaframe.GetTreeList().then((res) => {
                        commit("SET_MANALIST", res);
                    }),
                    Department.GetTreeList({
                        B_ManaframeId: "",
                        isDeep: true,
                    }).then((res) => {
                        commit("SET_DEPLIST", res);
                    }),
                    DataItem.GetTreeList("").then((res) => {
                        commit("SET_DATAITEMLIST", res);
                    }),
                    UserCenter.GetUserInfo().then((res) => {
                        if (util.validateNull(res.headIcon))
                            res.headIcon = defaultHeadIcon;
                        commit("SET_USERINFO", res);
                    })]).then(() => {
                        let authRoutes = filterAsyncRouter(rootState.user.menulist);
                        commit("SET_AUTHROUTES", authRoutes);
                        //根据后台传回的菜单数据动态添加路由
                        mergeRoutes(authRoutes);
                        resolve();
                    }).catch(error => {
                        reject(error)
                    })
            })
        },
        //清除用户缓存数据
        ClearStore({ state, commit }) {
            util.removeStore({ name: 'report', type: 'session' });
            util.removeStore({ name: 'tagslist', type: 'session' });
            util.removeStore({ name: 'userinfo', type: 'session' });
            util.removeStore({ name: 'menulist', type: 'session' });
            util.removeStore({ name: 'buttonlist', type: 'session' });
            util.removeStore({ name: 'manalist', type: 'session' });
            util.removeStore({ name: 'deplist', type: 'session' });
            util.removeStore({ name: 'dataitemlist', type: 'session' });
            util.removeStore({ name: 'token' });
            util.removeStore({ name: 'tokenexpire' });
            util.removeStore({ name: 'tokensilde' });
        },
    },
    mutations: {
        SET_USERINFO(state, userinfo) {
            state.userinfo = userinfo;
            util.setStore({ name: 'userinfo', content: state.userinfo, type: 'session' })
        },
        SET_MENULIST(state, menulist) {
            state.menulist = menulist;
            util.setStore({ name: 'menulist', content: menulist, type: 'session' })
        },
        SET_BUTTONLIST(state, buttonlist) {
            state.buttonlist = buttonlist;
            util.setStore({ name: 'buttonlist', content: state.buttonlist, type: 'session' })
        },
        SET_AUTHROUTES: (state, routes) => {
            state.authRoutes = routes;
        },
        SET_MANALIST(state, manalist) {
            state.manalist = manalist;
            util.setStore({ name: 'manalist', content: state.manalist, type: 'session' })
        },
        SET_DEPLIST(state, deplist) {
            state.deplist = deplist;
            util.setStore({ name: 'deplist', content: state.deplist, type: 'session' })
        },
        SET_DATAITEMLIST(state, dataitemlist) {
            state.dataitemlist = dataitemlist;
            util.setStore({ name: 'dataitemlist', content: state.dataitemlist, type: 'session' })
        },
        SET_TOKEN(state, token) {
            state.token = token;
            util.setStore({ name: 'token', content: state.token })
        },
        SET_TOKENEXPIRE(state, tokenexpire) {
            state.tokenexpire = tokenexpire;
            util.setStore({ name: 'tokenexpire', content: state.tokenexpire })
        },
        SET_TOKENSILDE(state, tokensilde) {
            state.tokensilde = tokensilde;
            util.setStore({ name: 'tokensilde', content: state.tokensilde })
        },
        SET_TOKENREFERENCE(state, { token, tokenexpire }) {
            this.commit('SET_TOKEN', token);
            let curTime = new Date();
            let expiredate = new Date(curTime.setMinutes(curTime.getMinutes() + tokenexpire));//定义过期时间（当前时间延后JWT时限）
            this.commit('SET_TOKENEXPIRE', expiredate);
            let sildetime = new Date(expiredate.setMinutes(expiredate.getMinutes() + 30));//定义滑动时间（过期时间延后30分钟）
            this.commit('SET_TOKENSILDE', sildetime);
        },
    },
}
export default user